/**
 * 
 */
package cc.rico.utils;

import java.io.IOException;

import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author rico 2016年8月20日
 *
 */
public class ZkUtil {
	private static final Logger logger = LoggerFactory.getLogger(ZkUtil.class);
	private static final String ZK_HOST = "127.0.0.1:2181";
	// 默认连接超时时间
	protected static final int DEFAULT_SESSION_TIMEOUT = 5000;
	
	/**
	 * 获取zk
	 * @param watch 
	 * @return
	 */
	public static ZooKeeper getInstance(Watcher watch) {
		ZooKeeper zk = null;
		try {
			zk = new ZooKeeper(ZK_HOST, DEFAULT_SESSION_TIMEOUT, watch);
			logger.info("success to get zk connection.");
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return zk;
	} 
	
	/**
	 * @param host
	 * @param watch
	 * @return
	 */
	public static ZooKeeper getInstance(String host, Watcher watch) {
		ZooKeeper zk = null;
		try {
			zk = new ZooKeeper(host, DEFAULT_SESSION_TIMEOUT, watch);
			logger.info("success to get zk connection.");
			
		} catch (IOException e) {
			e.printStackTrace();
		}
		
		return zk;
	} 
	
	/**
	 * 关闭zk
	 * @param zk
	 */
	public static void close(ZooKeeper zk) {
		try {
			if(zk != null) {
				zk.close();
			}
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}
}
